"""聊天机器人核心模块"""
import time
import random
import logging
from collections import defaultdict
from typing import Dict, List, Optional

from wxauto import WeChat
from .llm import Chat

class ChatBot:
    """聊天机器人类，用于微信集成"""

    def __init__(self, api_key: str, system_prompt: str, 
                 listen_list: List[str], merge_wait_time: float = 2.0):
        """初始化ChatBot实例
        
        Args:
            api_key (str): API密钥
            system_prompt (str): 系统提示词
            listen_list (List[str]): 需要监听的用户列表
            merge_wait_time (float, optional): 消息合并等待时间. 默认为 2.0
        """
        # 初始化DeepSeek实例
        self.deepseek = Chat(api_key=api_key, prompt=system_prompt)
        # 初始化微信实例
        self.wx = WeChat()
        # 保存配置
        self.listen_list = listen_list
        # 初始化消息缓冲区
        self.message_buffer = defaultdict(list)
        # 初始化时间记录
        self.last_message_time = defaultdict(float)
        # 设置合并等待时间
        self.merge_wait_time = merge_wait_time
        # 初始化聊天窗口缓存
        self.chat_windows: Dict = {}
        # 运行标志
        self.is_running = False
        
        # 初始化监听列表
        self._setup_listeners()

    def _setup_listeners(self) -> None:
        """设置监听器"""
        for name in self.listen_list:
            try:
                self.wx.AddListenChat(who=name)
                logging.info(f"添加监听: {name}")
            except Exception as e:
                logging.error(f"添加监听失败 - {name}: {str(e)}")

    def process_new_messages(self) -> float:
        """处理新消息
        
        Returns:
            float: 当前时间戳
        """
        try:
            msgs = self.wx.GetListenMessage()
            current_time = time.time()
            
            # 更新聊天窗口缓存
            for chat in msgs:
                msg = msgs.get(chat)
                self.chat_windows[chat] = msg
                
                for item in msg:
                    if item.type == 'friend':
                        self.message_buffer[item.sender].append(item.content)
                        self.last_message_time[item.sender] = current_time
                        logging.info(f"收到消息 - {item.sender}: {item.content}")
            
            return current_time
        except Exception as e:
            logging.error(f"处理新消息时出错: {str(e)}")
            return time.time()

    def send_reply(self, sender: str, reply: str) -> bool:
        """发送回复消息
        
        Args:
            sender (str): 发送者
            reply (str): 回复内容

        Returns:
            bool: 是否发送成功
        """
        try:
            for chat in self.chat_windows:
                msg = self.chat_windows.get(chat)
                for item in msg:
                    if item.type == 'friend' and item.sender == sender:
                        chat.SendMsg(reply)
                        logging.info(f"发送消息 - {sender}: {reply}")
                        return True
            return False
        except Exception as e:
            logging.error(f"发送回复时出错 - {sender}: {str(e)}")
            return False

    def process_buffered_messages(self, current_time: float) -> None:
        """处理缓冲区中的消息
        
        Args:
            current_time (float): 当前时间戳
        """
        for sender in list(self.message_buffer.keys()):
            try:
                if (current_time - self.last_message_time[sender] >= self.merge_wait_time 
                    and self.message_buffer[sender]):
                    
                    combined_message = "\n".join(self.message_buffer[sender])
                    logging.info(f"处理合并消息 - {sender}:\n{combined_message}")
                    
                    reply = self.deepseek.chat(combined_message, user_id=sender)
                    time.sleep(random.uniform(1, 3))  # 随机等待1-3秒
                    
                    if self.send_reply(sender, reply):
                        self.message_buffer[sender] = []  # 清空已处理的消息
                    
            except Exception as e:
                logging.error(f"处理缓冲消息时出错 - {sender}: {str(e)}")

    def run(self) -> None:
        """运行聊天机器人"""
        logging.info("ChatBot已启动，按Ctrl+C停止运行")
        self.is_running = True
        try:
            while self.is_running:
                current_time = self.process_new_messages()
                self.process_buffered_messages(current_time)
                time.sleep(0.5)  # 短暂休眠以减少CPU使用
        except KeyboardInterrupt:
            logging.info("ChatBot已停止运行")
        except Exception as e:
            logging.error(f"运行时出错: {str(e)}")
        finally:
            self.is_running = False

    def stop(self) -> None:
        """停止聊天机器人"""
        self.is_running = False
        # 清理资源
        self.message_buffer.clear()
        self.last_message_time.clear()
        self.chat_windows.clear()
        self.deepseek.clear_history()
        logging.info("ChatBot资源已清理") 